import os
import sys
import tkinter
from functools import partial
from config import BASC
from def_pack.doc_handle import DocHandle
from def_pack.frame_add_str import add_str, add_list_num, add_dict_num
from def_pack.get_the_frame_program2 import get_frame_program2
from def_pack.normal_solve import get_show_list, count_per_row_str_inlist, num_peop_to_dict, se_every_file_in_normal



def show_list_frame(filename):
    get_frame_program2(" ",filename,cls=1)

# def show_list_frame2(filename):
#     get_frame_program2(" ",filename)

def close_window(main_win):
    main_win.destroy()

def add_close_button(pii,main_win,h_numa,l_colu_numa):
    locals()[f"btn{pii}"] = tkinter.Button(main_win, text=f"关闭窗口", width=15, height=3,
                                           # padx=10, pady=10,
                                           bg="Lavender", font=("楷书", 11), fg="DeepSkyBlue",
                                           command=partial(close_window, main_win))
    locals()[f"btn{pii}"].grid(row=h_numa, column=1, padx=10, pady=20,columnspan=2)
    l_colu_numa = l_colu_numa + 1
    if l_colu_numa == 4:
        l_colu_numa = 0
        h_numa = h_numa + 1
    return l_colu_numa,h_numa,pii

#创建单个button按钮
def creat_each_button(kk,main_win,pii):
    pl1 = str(kk).rfind(".")
    pl2 = str(kk).rfind("/") + 1
    # title_pl2 = str(kk)[pl2:pl1]
    title_pl2 = str(kk)[pl2:int(pl2 + 4)]
    # get_frame_program2(" ", kk, BASC)
    locals()[f"btn{pii}"] = tkinter.Button(main_win, text=f"{title_pl2}", width=15, height=3,
                                           # padx=10, pady=10,
                                           bg="Wheat", font=("楷书", 11), fg="MediumBlue",
                                           command=partial(show_list_frame, kk))
    return pii,locals()[f"btn{pii}"]

def main_frame_program():
    dirpath = f"{BASC}/data/"
    title_pl=""
    sys.stdout = open(os.devnull, 'w')
    main_win = tkinter.Tk()
    main_win.iconbitmap(f'{BASC}/icon/Text-Docs.ico')

    #调整窗口位置
    main_win.geometry("605x770")
    main_win.geometry("+500+5")
    #设置窗口标题
    main_win.title(f"{title_pl}")

    # 获得每个要读取的数据文件
    filepathlist = se_every_file_in_normal(dirpath)

    #初始化行数，按钮数
    pii=0
    h_numa=0
    l_colu_numa=0

    #根据文件名，创建进入文件的button
    for kk in filepathlist:
        pii=pii+1
        # 创建进入文件的button
        pii,locals()[f"btn{pii}"]=creat_each_button(kk,main_win,pii)
        locals()[f"btn{pii}"].grid(row=h_numa,column=l_colu_numa,padx=10,pady=20)
        l_colu_numa=l_colu_numa+1
        if l_colu_numa==4:
            l_colu_numa=0
            h_numa=h_numa+1

    #这里是添加关闭窗口的
    if l_colu_numa == 0:
        l_colu_numa,h_numa,pii=add_close_button(pii,main_win,h_numa,l_colu_numa)
    else:
        h_numa = h_numa + 1
        l_colu_numa,h_numa,pii=add_close_button(pii,main_win,h_numa,l_colu_numa)
    main_win.mainloop()



if __name__ == '__main__':
    dirpath = f"{BASC}/"

    main_frame_program()
    pass
